package com.c.ctgproject.ui.sell.material

import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.c.ctgproject.R
import com.c.ctgproject.adapter.MaterialSellListAdapter
import com.c.ctgproject.base.BaseActivity
import com.c.ctgproject.entity.MaterialSellEntity
import com.c.ctgproject.utils.*
import kotlinx.android.synthetic.main.activity_sell_list.*
import kotlinx.android.synthetic.main.activity_sell_list.mRefresh

/**
 *作者:LiBW
 *创建日期: 2020/9/7
 *描述: 物料销售 页面
 */
class MaterialSellListActivity : BaseActivity() {
    private val mViewMode: MaterialSellListViewModel by lazy { ViewModelProvider(this)[MaterialSellListViewModel::class.java] }

    //默认展示第一页
    private var page = 1

    //默认每页展示条数
    private var size = 20

    //物料销售列表
    private val mList = ArrayList<MaterialSellEntity.ListBean>()
    private val mAdapter: MaterialSellListAdapter by lazy { MaterialSellListAdapter(this, mList) }
    override fun getLayout() = R.layout.activity_sell_list

    override fun event() {
        changeTransparentStatusBar()
        changeStatusIconColor(true)
        mMaterialSellListRV.adapter = mAdapter
        mMaterialSellListRV.layoutManager = LinearLayoutManager(this)
        loading.show()
        //物料销售列表回调
        mViewMode.list.observe(this, Observer {
            loading.dismiss()
            mRefresh.finishRefresh()
            mRefresh.finishLoadMore()
            MyLog.d("物料列表:$it")
            val data = initData(it)
            if (data.status == 0) {
                val entity = getGson().fromJson(data.data.handlerNull(), MaterialSellEntity::class.java)
                entity.list?.let { list ->
                    mList.addAll(list)
                    mAdapter.notifyDataSetChanged()
                }
            } else {
                CustomToast.showToast(this, data.msg.handlerNull())
            }
        })
        mViewMode.error.observe(this, Observer {
            MyLog.d("物料销售列表错误回调:$it")
            loading.dismiss()
            CustomToast.showToast(this, it)
        })
    }

    override fun click() {
        //下拉刷新监听
        mRefresh.setOnRefreshListener {
            page = 1
            mList.clear()
            mViewMode.getList(page, size)
        }
        //上拉加载
        mRefresh.setOnLoadMoreListener {
            page++
            mViewMode.getList(page, size)
        }
    }

    override fun onResume() {
        super.onResume()
        page = 1
        mList.clear()
        mViewMode.getList(page, size)
    }
}